/*
 * (C) APUE
 * Obtain the process time
 */
#include "apue.h"
#include <sys/times.h>

static void pr_times(clock_t, struct tms*, struct tms*);
static void do_cmd(char *);

int main(int argc, char* argv[])
{
	int i;
	setbuf(stdout, NULL);
	for (i = 1; i < argc; i++)
		do_cmd(argv[i]);
	exit(0);
}

static void do_cmd(char * cmd)
{
	struct tms tmsstart, tmsend;
	clock_t start, end;
	int status;
	printf("\ncommand: %s\n", cmd);

	if ((start = times(&tmsstart)) == -1)	/* starting values */
		err_quit("times error");

	if ((status = system(cmd)) < 0)	/* execute command */
		err_quit("system error");

	if ((end = times(&tmsend)) == -1)
		err_quit("times error");

	pr_times(end - start, &tmsstart, &tmsend);
	pr_exit(status);
}

static void pr_times(clock_t real, struct tms *tmsstart, struct tms *tmsend)
{
	static long clkck = 0;
	if (clkck == 0)	/* fetch clock ticks per second first time */
		if ((clkck = sysconf(_SC_CLK_TCK)) < 0)
			err_quit("sysconf error");

	/* print different times */
	printf(" real:%7.2f\n", real / (double)clkck);
	printf(" user:%7.2f\n", (tmsend->tms_utime - tmsstart->tms_utime) / (double)clkck);
	printf("  sys:%7.2f\n", (tmsend->tms_stime - tmsstart->tms_stime) / (double)clkck);
	printf(" child user:%7.2f\n", (tmsend->tms_cutime - tmsstart->tms_cutime) / (double)clkck);
	printf("  child sys:%7.2f\n", (tmsend->tms_cstime - tmsstart->tms_cstime) / (double)clkck);
}
